<template>
  <div>
    <el-card>
      <div>
        <!--主页视图区域-->
        <!--图片区域-->
        <div class="block" v-if="!(checkout === 0 || checkout === 1)">
          <div class="condition">
            <div class="text1">{{type === 'add' ? '手动入库' : '入库修改'}}</div>
          </div>
          <div class="bg-card">
            <el-form :inline="true" :model="topForm" ref="topForm" :rules="topFormRule">
              <el-row>
                <el-form-item prop="value1" label="入库单号" v-if="type !== 'add'">
                  <el-input v-model="inboundNum" disabled style="width:150px"></el-input>
                </el-form-item>
                <el-form-item prop="value2" label="仓库">
                  <el-input value="备品备件仓库" disabled></el-input>
                </el-form-item>
                <el-form-item label="入库单填写时间">
                  <el-date-picker
                    v-model="inboundApplyTime"
                    type="date"
                    format="yyyyMMdd"
                    value-format="yyyyMMdd"
                    :picker-options="pickerOptions"
                    :disabled="type === 'view'"
                    placeholder="选择日期"
                  ></el-date-picker>
                </el-form-item>
                <el-form-item prop="inboundType" label="入库类型" v-if="type !== 'view'">
                  <el-select v-model="topForm.inboundType" value="新增入库" :disabled="type === 'add'">
                    <el-option
                      v-for="item in inboundTypeOpt"
                      :key="item"
                      :label="item"
                      :value="item"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-row>
              <el-row v-if="type !== 'view'">
                <el-form-item prop="goodsId01" label="货品编号">
                  <el-input v-model="topForm.goodsId01" style="width:100px"></el-input>
                </el-form-item>
                <el-form-item prop="goodsName" label="货品名称">
                  <el-input v-model="topForm.goodsName" style="width:100px"></el-input>
                </el-form-item>
                <el-form-item prop="specification" label="型号规格">
                  <el-input v-model="topForm.specification"></el-input>
                </el-form-item>
                <el-form-item prop="goodsUnit" label="单位">
                  <el-input v-model="topForm.goodsUnit" style="width:80px"></el-input>
                </el-form-item>
                <el-form-item prop="inboundGoodsNumber" label="数量">
                  <el-input v-model="topForm.inboundGoodsNumber" style="width:80px"></el-input>
                </el-form-item>
              </el-row>
              <el-row v-if="type !== 'view'">
                <el-form-item prop="goodsPrime" label="保存期限">
                  <el-date-picker
                    v-model="topForm.goodsPrime"
                    type="date"
                    format="yyyyMMdd"
                    value-format="yyyyMMdd"
                    :disabled="type === 'view'"
                    placeholder="选择日期"
                  ></el-date-picker>
                </el-form-item>
                <el-form-item prop="inboundRemarks"  label="备注">
                  <el-input v-model="topForm.inboundRemarks" type="textarea" style="width:200px;;margin-top:30px"></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" style="margin-top:28px" @click="handleTopSubmit">新增货品</el-button>
                </el-form-item>
              </el-row>
            </el-form>
          </div>
        </div>
        <br />
        <div  v-if="type === 'add' ">
          <div class="condition" style="margin-top:30px">
            <div class="title">批量入库</div>
          </div>
          <div class="bg-card">
            <el-form :inline="true" :model="midForm" ref="midForm">
              <el-form-item>
                <el-upload
                  class="upload-demo"
                  action="/api/restful/v1/dd/inbound/uploadEvaluateExcel"
                  :data="{inboundApplyTime}"
                  :on-success="handleUploadSuccess" ref="upload" :headers="headers">
                  <el-button
                    style="margin-top:28px"
                    type="primary"
                  >上传入库单模板<i class="el-icon-upload el-icon--right"></i></el-button>
                </el-upload>
              </el-form-item>
              <el-form-item>
                <el-button type="success" @click="handleEvaluationExcel" style="margin-top:28px">批量入库</el-button>
              </el-form-item>
              <el-form-item>
                <el-button @click="downloadTemplate" style="margin-left:50px;margin-top:28px">下载入库单模板</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <div class="condition" style="margin-top:30px" v-if="!checkout">
          <div class="title">入库单货品展示</div>
        </div>
        <div class="bg-card" v-if="type !== 'view'">
          <el-button type="danger" @click="handleDel" style="margin-left:30px">删除</el-button>
          <el-button @click="handleSubmit(0)" style="margin-left:30px">保存入库单</el-button>
          <el-button type="primary" @click="handleSubmit(1)" style="margin-left:30px">提交</el-button>
          <el-button type="info" @click="handleReturn" style="margin-left:30px">返回</el-button>
        </div>
        <br />
        <el-table
          :data="newlist"
          border
          style="width: 100%"
          ref="table"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" v-if="type !== 'view'"></el-table-column>
          <el-table-column type="index" label="序号" width="100" align="center"></el-table-column>
          <el-table-column prop="goodsId01" label="货品编号" align="center"></el-table-column>
          <el-table-column prop="goodsName" label="货品名称" align="center"></el-table-column>
          <el-table-column prop="specification" label="型号规格" align="center"></el-table-column>
          <el-table-column prop="inboundType" label="入库类型" align="center"></el-table-column>
          <el-table-column prop="goodsUnit" label="单位" align="center"></el-table-column>
          <el-table-column prop="inboundGoodsNumber" label="数量" align="center"></el-table-column>
          <el-table-column prop="goodsPrime" label="保存期限" align="center"></el-table-column>
          <el-table-column prop="inboundRemarks" label="备注" align="center"></el-table-column>
        </el-table>
        <el-button v-if="checkout === 0 " type="primary" @click="handleReturn" style="margin:30px 0 0 30px">返回</el-button>
        <div class="block" style="float:right;margin-bottom:10px">
          <span class="demonstration"></span>
          <el-pagination
            :current-page.sync="page"
            :page-size="10"
            layout="total, prev, pager, next"
            :total="total"
          ></el-pagination>
        </div>
      </div>
      <div class="bg-card" v-if="checkout" style="margin-top:30px">
        <div style="margin-top:20px">
              <el-input
                type="textarea"
                :rows="3"
                placeholder="请输入审核意见"
                v-model="textarea">
              </el-input>
          </div>
        <el-button type="success" @click="handleCheckout(1)" style="margin-left:30px;margin-top:30px">同意</el-button>
        <el-button type="info" @click="handleCheckout(2)" style="margin-left:30px">退回</el-button>
        <el-button @click="handleReturn" style="margin-left:30px">返回</el-button>
      </div>
    </el-card>
  </div>
</template>
<script>
import FileSaver from "file-saver";
export default {
  data() {
    return {
      headers: {
        Authorization: sessionStorage.getItem("User_Code")
      },
      page: 1,
      total: 0,
      topFormRule: {
        goodsId01: [{ required: true, message: "必填项", trigger: "blur" }],
        goodsName: [{ required: true, message: "必填项", trigger: "blur" }],
        specification: [{ required: true, message: "必填项", trigger: "blur" }],
        goodsUnit: [{ required: true, message: "必填项", trigger: "blur" }],
        inboundGoodsNumber: [
          { required: true, message: "必填项", trigger: "blur" },
        ],
        inboundType: [{ required: true, message: "必填项", trigger: "change" }],
        goodsPrime: [{ required: true, message: "必填项", trigger: "change" }],
        waringValue: [{ required: true, message: "必填项", trigger: "change" }],
      },
      initTopForm: {
        goodsId01: "",
        goodsName: "",
        inboundGoodsNumber: "",
        goodsPrime: "",
        goodsUnit: "",
        inboundRemarks: "",
        inboundType: "新增入库",
        specification: "",
        warehouse: 2,
        waringValue: 0,
      },
      uploadFile: {
        url: "",
      },
      query: {
        currentPage: 0,
        num: '',
        pageSize: 0
      },
      topForm: {},
      midForm: {},
      inboundApplyTime: "",
      status: 0,
      tableData: [],
      selectData: [],
      type: "add",
      inboundGoodsNumber: "",
      checkout: null,
      wareHouse: 2,
      inboundTypeOpt: ["新增入库", "退还入库", "报废未批准"],
      textarea: '',
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              picker.$emit("pick", new Date());
            },
          },
          {
            text: "昨天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit("pick", date);
            },
          },
          {
            text: "一周前",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", date);
            },
          },
        ],
      },
    };
  },
  created() {
    this.type = this.$route.query.type;
    this.query.num = this.$route.query.inboundNum;
    this.inboundNum = this.$route.query.inboundNum
    this.inboundApplyTime = this.$route.query.inboundFillTime;
    this.checkout = Number(this.$route.query.checkout);
    this.topForm = Object.assign({}, this.initTopForm);
    switch (this.type) {
      case "add": {
        break;
      }
      case "edit":
      case "view": {
        this.fetch();
        break;
      }
    }
  },
  async mounted() {
    this.$refs.table.toggleAllSelection();
    const res2 = await this.$http.get(`/restful/v1/dd/permit/getUserDetail?${Math.random()}`);
    this.topForm.inboundPeople = res2.data.object.userName
  },
  methods: {
    handleTopSubmit() {
      if (!this.inboundApplyTime) {
        return this.$message.info("请填写入库时间");
      }
      this.topForm.inboundx = this.inboundApplyTime // 修改了
      this.$refs.topForm.validate((valid) => {
        if (valid) {
          this.tableData.push(
            Object.assign({ id: this.tableData.length }, this.topForm)
          );
          this.$refs.topForm.resetFields();
          this.$refs.table.toggleRowSelection(
            this.tableData[this.tableData.length - 1]
          );
        }
      });
    },
    async handleEvaluationExcel() {
      if (this.uploadFile.url) {
        try {
          const res = await this.$http.post(
            `/restful/v1/dd/inbound/importInboundGoods?path=${this.uploadFile.url}&wareHouse=${this.wareHouse}`
          );
          if (res.data.code === 1) {
            this.$message.success("操作成功");
            this.uploadFile.url = "";
            this.$router.push({
              path: "/home/storehouse2/acceptance",
            });
          } else {
            this.$message.error(res.data.message);
          }
        } catch (error) {
          this.$message.error("服务器错误");
        }
      }
    },
    handleSelectionChange(val) {
      this.selectData = val;
    },
    async handleSubmit(status) {
      if (this.tableData.length === 0) {
        return this.$message.info("没有需要提交的信息")
      }
      if (!this.inboundApplyTime) {
        return this.$message.info("请填写入库时间");
      }
      let res = null
      if (status) {
        res = await this.$http.post(
          `/restful/v1/dd/inbound/inboundGoodsFilling?inboundApplyTime=${this.inboundApplyTime}&status=${status}&inboundNum=${this.inboundNum}`,
          this.tableData
        );
      } else {
        res = await this.$http.post(
          `/restful/v1/dd/inbound/inboundGoodsFilling?inboundApplyTime=${this.inboundApplyTime}&status=${status}&inboundNum=${this.inboundNum}`,
          this.selectData
        );
      }
      if (res.data.code === 1) {
        this.$message.success("操作成功");
        this.$router.push({
          path: "/home/storehouse2/acceptance",
        });
      } else {
        this.$message.error(res.data.message);
      }
    },
    // edit or view
    async fetch() {
      const { data } = await this.$http.post(
        `/restful/v1/dd/inbound/getGoodDetailByInboundNum`,
        this.query
      );
      if (data.code === 1 && data.object) {
        this.tableData = data.object.dataList;
        this.total = data.object.dataList.length
        for (let i = 0; i < this.tableData.length; i++) {
          this.tableData[i].id = i
        }
        this.$nextTick(function() {
          this.tableData.forEach(item => {
            this.$refs.table.toggleRowSelection(item, true);
          })
        })
      }
    },
    handleUploadSuccess(res) {
      if (res.code == 1) {
        this.$message.success(res.message);
        // this.uploadFile.inboundApplyTime = this.inboundApplyTime;
        this.uploadFile.url = res.object;
      } else {
        this.$message.error(res.message);
      }
    },
    async downloadTemplate() {
      //下载模板
      const { data } = await this.$http.get(
        "/restful/v1/dd/inbound/downloadInboundExcel",
        {
          responseType: "blob",
        }
      );
      try {
        FileSaver.saveAs(
          new Blob([data], { type: "application/octet-stream" }),
          "入库单模板.xls"
        );
      } catch (error) {
        this.$message.error("服务器繁忙")
        console.log(111111, error.message);
      }
    },
    async handleDel() {
      if (this.type === 'edit') {
        const idx = this.selectData.map((el) => el.id);
        for (let i = 0; i < idx.length; i++) {
          const res = await this.$http.post(`/restful/v1/dd/inbound/deletePreserveGoods?inboundNum=${this.inboundNum}&goodId=${this.tableData[idx[i] - i].goodsId01}`)
          if (res.data.code === 1) {
            this.$message.success("删除成功");
          } else {
            this.$message.error(res.data.message)
          }
          this.selectData.splice(idx[i] - i, 1);
          this.tableData.splice(idx[i] - i, 1);
        }
        if (this.tableData.length === 0) {
          this.handleReturn()
        }
        this.fetch()
      } else {
        const idx = this.selectData.map((el) => el.id);
        for (let i = 0; i < this.selectData.length; i++) {
          for (let j = 0; j < idx.length; j++) {
            if (this.selectData[i].id === idx[j]) {
              this.selectData.splice(i, 1);
            }
          }
        }
        for (let i = 0; i < this.tableData.length; i++) {
          for (let j = 0; j < idx.length; j++) {
            if (this.tableData[i].id === idx[j]) {
              this.tableData.splice(i, 1);
            }
          }
        }
      }
    },
    async handleCheckout(status) {
      if (status === 1) {
        this.$confirm('是否同意审核', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const { data } = await this.$http.post(
            encodeURI(`/restful/v1/dd/inbound/checkInboundGoods?inboundNum=${this.inboundNum}&checkApplication=${status}&inboundSubReason=${this.textarea}`)
          );
          if (data.code === 1) {
            this.$message.success("操作成功");
            this.$router.go(-1);
            return;
          }
          this.$message.error(data.message);
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          })
        });
      } else if (status === 2) {
        if (!this.textarea) {
          return this.$message.info('请填写审核意见')
        }
        this.$confirm('是否不同意审核', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const { data } = await this.$http.post(
            encodeURI(`/restful/v1/dd/inbound/checkInboundGoods?inboundNum=${this.inboundNum}&checkApplication=${status}&inboundSubReason=${this.textarea}`)
          );
          if (data.code === 1) {
            this.$message.success("操作成功");
            this.$router.go(-1);
            return;
          }
          this.$message.error(data.message);
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          })
        });
      }
    },
    handleReturn () {
      this.$router.go(-1);
    },
  },
  computed: {
    newlist() {
      return this.tableData.slice((this.page - 1) * 10, this.page * 10);
    }
  },
};
</script>
